#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
直接启动数据库查看器 - 使用绝对路径
"""

import sys
import os

# 添加父目录到路径
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

try:
    from database_server import DatabaseServer, DatabaseConfig
    from storage_engine import CachePolicy
except ImportError as e:
    print(f"❌ 导入错误: {e}")
    sys.exit(1)

def main():
    """直接启动查看器"""
    print("🔍 数据库结构查看器")
    print("=" * 50)
    
    # 使用绝对路径
    demo_data_path = "/Users/xiazixuan/大三上/实训/code/OperatingSystem/demo_data"
    
    print(f"📁 数据库路径: {demo_data_path}")
    print(f"📁 路径存在: {os.path.exists(demo_data_path)}")
    
    if not os.path.exists(demo_data_path):
        print("❌ 数据库路径不存在")
        return
    
    try:
        config = DatabaseConfig(
            db_path=demo_data_path,
            cache_size=50,
            cache_policy=CachePolicy.LRU,
            enable_locking=False
        )
        
        server = DatabaseServer(config)
        server.start()
        session = server.create_session()
        
        print("✅ 服务器启动成功！")
        print("\n可用命令:")
        print("  show databases - 显示所有数据库")
        print("  use <db_name>  - 切换数据库")
        print("  show tables    - 显示表列表")
        print("  desc <table>   - 显示表结构")
        print("  select <table> [limit] - 显示表数据")
        print("  quit           - 退出")
        print()
        
        current_db = None
        
        while True:
            try:
                prompt = f"({current_db if current_db else 'none'}) > "
                command = input(prompt).strip()
                
                if not command:
                    continue
                
                parts = command.split()
                cmd = parts[0].lower()
                
                if cmd == 'quit':
                    break
                elif cmd == 'show':
                    if len(parts) >= 2 and parts[1].lower() == 'databases':
                        databases = server.list_databases(session)
                        print(f"\n📊 数据库列表:")
                        print("=" * 40)
                        if databases:
                            for i, db_name in enumerate(databases, 1):
                                print(f"{i}. 📁 {db_name}")
                        else:
                            print("💡 暂无数据库")
                        print()
                    elif len(parts) >= 2 and parts[1].lower() == 'tables':
                        if current_db:
                            db_instance = server.database_manager.get_database(current_db)
                            tables = db_instance.list_tables()
                            print(f"\n📋 数据库 '{current_db}' 中的表:")
                            if tables:
                                for i, table_name in enumerate(tables, 1):
                                    records = db_instance.select_records(table_name)
                                    print(f"{i}. 📊 {table_name} ({len(records)} 条记录)")
                            else:
                                print("💡 暂无表")
                            print()
                        else:
                            print("❌ 请先选择数据库\n")
                    else:
                        print("❌ 未知的 show 命令 (databases/tables)\n")
                elif cmd == 'use':
                    if len(parts) >= 2:
                        db_name = parts[1]
                        try:
                            server.use_database(session, db_name)
                            current_db = db_name
                            print(f"✅ 已切换到数据库: {db_name}\n")
                        except Exception as e:
                            print(f"❌ 切换失败: {e}\n")
                    else:
                        print("❌ 请指定数据库名称\n")
                elif cmd == 'desc':
                    if len(parts) >= 2:
                        table_name = parts[1]
                        if current_db:
                            try:
                                db_instance = server.database_manager.get_database(current_db)
                                schema = db_instance.storage_engine.table_schemas.get(table_name)
                                if schema:
                                    print(f"\n📋 表结构: {current_db}.{table_name}")
                                    print("=" * 60)
                                    print(f"{'字段名':<15} {'类型':<12} {'长度':<8} {'主键':<6}")
                                    print("-" * 60)
                                    for col in schema.columns:
                                        pk_mark = "是" if col.primary_key else "否"
                                        length_info = str(col.length) if col.length else "N/A"
                                        print(f"{col.name:<15} {col.type.name:<12} {length_info:<8} {pk_mark:<6}")
                                    print()
                                else:
                                    print(f"❌ 表 {table_name} 不存在\n")
                            except Exception as e:
                                print(f"❌ 获取表结构失败: {e}\n")
                        else:
                            print("❌ 请先选择数据库\n")
                    else:
                        print("❌ 请指定表名称\n")
                elif cmd == 'select':
                    if len(parts) >= 2:
                        table_name = parts[1]
                        limit = int(parts[2]) if len(parts) >= 3 else 5
                        if current_db:
                            try:
                                db_instance = server.database_manager.get_database(current_db)
                                records = db_instance.select_records(table_name)
                                
                                print(f"\n📊 表数据: {current_db}.{table_name}")
                                print("=" * 60)
                                print(f"总记录数: {len(records)}, 显示前 {min(limit, len(records))} 条\n")
                                
                                if records:
                                    for i, record in enumerate(records[:limit], 1):
                                        print(f"{i}. {record}")
                                    if len(records) > limit:
                                        print(f"... 还有 {len(records) - limit} 条记录")
                                else:
                                    print("💡 表中暂无数据")
                                print()
                            except Exception as e:
                                print(f"❌ 查询失败: {e}\n")
                        else:
                            print("❌ 请先选择数据库\n")
                    else:
                        print("❌ 请指定表名称\n")
                else:
                    print(f"❌ 未知命令: {command}")
                    print("💡 输入可用命令: show databases, use <db>, show tables, desc <table>, select <table>, quit\n")
                    
            except KeyboardInterrupt:
                print("\n👋 退出程序")
                break
            except EOFError:
                print("\n👋 退出程序")
                break
        
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        try:
            server.stop()
        except:
            pass

if __name__ == "__main__":
    main()
